<template>
  <view class="accounting-container">
    <!-- 收支统计卡片 -->
    <view class="summary-cards">
      <view class="summary-card">
        <view class="summary-title">收入</view>
        <view class="summary-amount income" :class="{'amount-sm': totalIncome.length > 8, 'amount-xs': totalIncome.length > 10}">
          {{ totalIncome }}
        </view>
      </view>
      <view class="summary-card">
        <view class="summary-title">支出</view>
        <view class="summary-amount expense" :class="{'amount-sm': totalExpense.length > 8, 'amount-xs': totalExpense.length > 10}">
          {{ totalExpense }}
        </view>
      </view>
      <view class="summary-card">
        <view class="summary-title">结余</view>
        <view class="summary-amount" :class="{ 
          'income': netBalance >= 0, 
          'expense': netBalance < 0,
          'amount-sm': netBalance.toString().length > 8,
          'amount-xs': netBalance.toString().length > 10
        }">
          {{ netBalance }}
        </view>
      </view>
    </view>
    
    <!-- 筛选按钮 -->
    <view class="filter-buttons">
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'all' }"
        @tap="filterRecords('all')"
      >全部</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === '收入' }"
        @tap="filterRecords('收入')"
      >收入</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === '支出' }"
        @tap="filterRecords('支出')"
      >支出</view>
    </view>
    
    <!-- 记账列表 -->
    <view class="record-list">
      <view class="empty-tip" v-if="filteredRecords.length === 0">
        <image class="empty-icon" src="/static/data-empty.png" mode="aspectFit"></image>
        <text class="empty-text">暂无记账数据</text>
      </view>
      
      <view 
        class="record-item" 
        v-for="(record, index) in filteredRecords" 
        :key="record.id"
        @tap="editRecord(record)"
      >
        <view class="record-content">
          <view class="record-title">{{ record.title }}</view>
          <view class="record-desc">{{ record.account || '微信' }} {{ formatDate(record.date) }}</view>
        </view>
        <view class="record-amount" :class="{ 'income-text': record.accountType === '收入', 'expense-text': record.accountType === '支出' }">
          {{ record.accountType === '收入' ? '+' : '-' }}{{ parseFloat(record.amount).toFixed(2) }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { onShow } from '@dcloudio/uni-app'; // 添加 onShow 导入
import TransactionApi from '@/sheep/api/money/transaction';

const props = defineProps({
  accountingData: {
    type: Array,
    default: () => []
  },
  contactId: {
    type: String,
    required: true
  },
  currentTab: {
    type: Number,
    default: 0
  },
  tabIndex: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['refresh', 'filter-records', 'longpress']);

const currentFilter = ref('all');
const filteredRecords = ref([]);
const accountingList = ref([]); // 添加本地数据存储

// 添加长按处理函数
const onLongPress = (item) => {
  emit('longpress', item, 'more');
};

// 计算总收入
const totalIncome = computed(() => {
  return accountingList.value
    .filter(record => record.accountType === '收入')
    .reduce((sum, record) => sum + parseFloat(record.amount), 0)
    .toFixed(2);
});

// 计算总支出
const totalExpense = computed(() => {
  return accountingList.value
    .filter(record => record.accountType === '支出')
    .reduce((sum, record) => sum + parseFloat(record.amount), 0)
    .toFixed(2);
});

// 计算净余额
const netBalance = computed(() => {
  return (parseFloat(totalIncome.value) - parseFloat(totalExpense.value)).toFixed(2);
});

// 筛选记录
const filterRecords = (type) => {
  currentFilter.value = type;
  if (type === 'all') {
    filteredRecords.value = accountingList.value;
  } else {
    filteredRecords.value = accountingList.value.filter(record => record.accountType === type);
  }
  emit('filter-records', type);
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  try {
    // 如果是时间戳（数字或数字字符串）
    if (!isNaN(dateString)) {
      const date = new Date(Number(dateString));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
    
    // 确保 dateString 是字符串类型
    const dateStr = String(dateString);
    
    // 如果日期包含时间，只显示日期部分
    if (dateStr.includes(' ')) {
      return dateStr.split(' ')[0];
    }
    
    return dateStr;
  } catch (error) {
    console.error('日期格式化错误:', error, dateString);
    return String(dateString);
  }
};

// 加载人情收支数据
const loadAccountingData = async () => {
  if (!props.contactId) {
    console.error('联系人ID不存在，无法加载数据');
    return;
  }
  
  console.log('记账tab 开始加载数据 - contactId:', props.contactId);
  
  try {
    const res = await TransactionApi.queryHumanTransactions({
      contactId: props.contactId
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 处理数据，转换为组件需要的格式
      accountingList.value = res.data.map(item => ({
        id: item.id,
        title: item.eventName || item.eventTypeName || '未命名',
        amount: item.giftAmount || 0,
        accountType: item.transactionType === 'IN' ? '收入' : '支出',
        account: item.accountType ? getAccountName(item.accountType) : '微信',
        date: item.eventDate || '', // 使用 eventDate 作为显示时间
        remark: item.remark || '',
        eventTypeId: item.eventTypeId // 保存类型ID
      }));
      
      // 应用当前筛选条件
      filterRecords(currentFilter.value);
      
      console.log('记账tab 数据加载成功，共', accountingList.value.length, '条记录');
      
      // 通知父组件刷新完成
      emit('refresh');
    } else {
      console.error('获取人情收支列表失败:', res.msg);
      accountingList.value = [];
      filteredRecords.value = [];
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取人情收支列表失败:', error);
    accountingList.value = [];
    filteredRecords.value = [];
  }
};

// 编辑记录
const editRecord = (item) => {
  // 确保有记录ID
  if (!item || !item.id) {
    uni.showToast({
      title: '记录ID不存在',
      icon: 'none'
    });
    return;
  }
  
  // 跳转到编辑页面，传递必要参数
  uni.navigateTo({
    url: `/pages/contact/accounting-edit?contactId=${props.contactId}&id=${item.id}&mode=edit`
  });
};

// 账户类型映射
const getAccountName = (accountType) => {
  const accountTypeMap = {
    'WCHAT': '微信',
    'ALIPAY': '支付宝',
    'MONEY': '现金',
    'BANK_CARD': '银行卡',
    'OTHER': '其他'
  };
  return accountTypeMap[accountType] || '微信';
};

// 使用 onShow 生命周期钩子，当页面显示时刷新数据
onShow(() => {
  if (props.currentTab === props.tabIndex) {
    loadAccountingData();
  }
});

// 暴露方法给父组件调用
defineExpose({
  loadAccountingData
});

</script>

<style lang="scss" scoped>
.accounting-container {
  padding: 20rpx 0;
  background-color: #f5f5f5;
  min-height: 100%;
}

.summary-cards {
  display: flex;
  margin: 0 20rpx 20rpx;
  gap: 20rpx;
}

.summary-card {
  flex: 1;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.summary-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 16rpx;
}

.summary-amount {
  font-size: 22px; // 默认字体大小
  font-weight: 600;
  word-break: break-all; // 允许在任意字符间断行
  line-height: 1.2; // 调整行高
}

// 根据数字长度添加不同的字体大小类
.amount-sm {
  font-size: 18px; // 数字较多时的字体大小
}

.amount-xs {
  font-size: 16px; // 数字很多时的字体大小
}

.summary-amount.income {
  color: #2196F3;
}

.summary-amount.expense {
  color: #FF9800;
}

.filter-buttons {
  display: flex;
  margin: 0 20rpx 20rpx;
  gap: 16rpx;
}

.filter-btn {
  padding: 12rpx 32rpx;
  font-size: 14px;
  color: #666;
  background-color: #f0f0f0;
  border-radius: 30rpx;
  text-align: center;
}

.filter-btn.active {
  color: #fff;
  background-color: #2196F3;
  border-color: transparent;
  font-weight: 500;
}

.record-list {
  margin: 0 20rpx;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.record-content {
  flex: 1;
}

.record-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 8rpx;
}

.record-desc {
  font-size: 12px;
  color: #999;
}

.record-amount {
  font-size: 18px;
  font-weight: 600;
}

.income-text {
  color: #2196F3;
}

.expense-text {
  color: #FF9800;
}

/* 空数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>


